package com.cote.douhahou.pretloan.level;

import static com.cote.douhahou.pretloan.utils.AkomapaLendConfigs.PermissionCHome;
import static com.cote.douhahou.pretloan.home.PersonalCenterFragment.User_Avatar;
import static com.cote.douhahou.pretloan.utils.AkomapaLendConfigs.PermissionCCamera;
import static com.cote.douhahou.pretloan.utils.AkomapaLendConfigs.StepPersonal;
import static com.cote.douhahou.pretloan.utils.AkomapaLendConfigs.StepWork;

import android.Manifest;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.cote.douhahou.pretloan.any.util.AkomapalendAnalyticsUtil;
import com.cote.douhahou.pretloan.beans.OtheAkomapalendrsInfo;
import com.cote.douhahou.pretloan.beans.PersAkomapalendonalInfo;
import com.cote.douhahou.pretloan.beans.ProcessInAkomapalendfo;
import com.cote.douhahou.pretloan.launcher.BaseContext;
import com.cote.douhahou.pretloan.msg.widget.OcrVieAkomapalendwManager;
import com.cote.douhahou.pretloan.network.HttpHelper;
import com.cote.douhahou.pretloan.service.CusServiceAkomapalendDialog;
import com.cote.douhahou.pretloan.utils.PhotoAkomapalendSelectorDialog;
import com.cote.douhahou.pretloan.utils.image_akomapalend.ImageConvert;
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil;
import com.cote.douhahou.pretloan.R;
import com.cote.douhahou.pretloan.beans.AppAkomapalendConfigCustomize;
import com.cote.douhahou.pretloan.apply.LoanApplyActivity;
import com.cote.douhahou.pretloan.msg.MessageActivity;
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class VipAkomapalendInfoActivity extends AppCompatActivity implements EasyPermissions.RationaleCallbacks,EasyPermissions.PermissionCallbacks {

    private ImageView userAvatarIv;
    private TextView userNameTv;
    private TextView userGenderTv;
    private TextView expValueTv;
    private View vipBgView;
    private ImageView vipImgIv;
    private TextView vipTv;
    private CircleAkomapalendBarView vipCpb;
    private TextView vipExpDescTv;
    private View fillInJobInfoView;
    private TextView fillInJobInfoBtn,fillInPersonalInfoBtn;

    private ActivityResultLauncher<PickVisualMediaRequest> pickMediaLauncher;

    private Runnable cameraRunnable;

    public String imagePath = "";
    public Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_level_info);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        userAvatarIv = findViewById(R.id.avia_iv_user_avatar);
        userNameTv = findViewById(R.id.avia_tv_user_name);
        userGenderTv = findViewById(R.id.avia_tv_user_gender);
        expValueTv = findViewById(R.id.avia_tv_exp_value);
        vipBgView = findViewById(R.id.avia_view_vip_bg);
        vipImgIv = findViewById(R.id.avia_iv_vip_img);
        vipTv = findViewById(R.id.avia_tv_vip);
        vipCpb = findViewById(R.id.avia_cpb_vip);
        vipExpDescTv = findViewById(R.id.avia_tv_vip_exp_desc);
        fillInJobInfoView = findViewById(R.id.avia_view_fill_in_job_info);
        fillInJobInfoBtn = findViewById(R.id.avia_btn_fill_in_job_info);
        fillInPersonalInfoBtn = findViewById(R.id.avia_btn_fill_in_personal_info);

        init();

    }

    private void init(){

        findViewById(R.id.avia_ib_back).setOnClickListener(v -> onBackPressed());
        findViewById(R.id.avia_ib_customer_service).setOnClickListener(v -> new CusServiceAkomapalendDialog(this).show());

        userAvatarIv.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("VIP","AVATAR_CLICK","");

            new PhotoAkomapalendSelectorDialog(
                    this,
                    this::startCamera,
                    this::openAlbum
            ).show();
        });

        SwipeRefreshLayout refreshLayout = findViewById(R.id.avia_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            HttpHelper.inst().submitEvent("VIP","REFRESH_CLICK","");
            refreshLayout.setRefreshing(false);
            HttpHelper.inst().process(this,this::refreshMsg);
        });

        pickMediaLauncher = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                this.uri = uri;
                imagePath = ImageConvert.bitmapFilePathFromURI(this, this.uri);
                onPhotoGet_akomapalend();
            }
        });

        refreshUserInfo();

    }

    @Override
    protected void onResume() {
        super.onResume();
        HttpHelper.inst().submitEvent("VIP","START","");
        HttpHelper.inst().process(this,this::refreshMsg);
    }

    @Override
    protected void onPause() {
        super.onPause();
        HttpHelper.inst().submitEvent("VIP","END","");
    }


    private void refreshMsg(){

        if (ProcessInAkomapalendfo.instance().getSteps_akomapalend().contains(StepPersonal)){
            fillInPersonalInfoBtn.setText(getString(R.string.vip_info_go));
            fillInPersonalInfoBtn.setTextColor(Color.parseColor("#FF49280B"));
            fillInPersonalInfoBtn.setBackgroundResource(R.drawable.back_gradient_yellow_round_c_b);
            fillInPersonalInfoBtn.setOnClickListener(v -> {
                HttpHelper.inst().submitEvent("VIP","PERSONAL_INFO_CLICK","");

                String[] homePermissions = AppAkomapalendConfigCustomize.instance().getHomePermission_akomapalend();

                if (AkomapaLendUtil.permissionsHasAgree(this, homePermissions)) {
                    //device info upload
                    try {
                        if (AkomapaLendUtil.hasLogin()) {
                            AkomapalendAnalyticsUtil.INSTANCE.saveDeviceS2SInfo();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    HttpHelper.inst().process(this,() -> {
                        if (ProcessInAkomapalendfo.instance().getSteps_akomapalend().isEmpty())
                            startActivity(new Intent(this, LoanApplyActivity.class));
                        else startActivity(new Intent(this, MessageActivity.class));
                    });

                } else
                    EasyPermissions.requestPermissions(this, getString(R.string.request_permission_all), PermissionCHome, homePermissions);

            });
        }

        else {
            fillInPersonalInfoBtn.setOnClickListener(null);
            fillInPersonalInfoBtn.setText(getString(R.string.vip_info_received));
            fillInPersonalInfoBtn.setTextColor(Color.parseColor("#80FFFFFF"));
            fillInPersonalInfoBtn.setBackgroundResource(R.drawable.back_brown_round_c);
        }

        if (!ProcessInAkomapalendfo.instance().getAllSteps_akomapalend().contains(StepWork))
            fillInJobInfoView.setVisibility(View.GONE);

        else {
            fillInJobInfoView.setVisibility(View.VISIBLE);

            if (ProcessInAkomapalendfo.instance().getSteps_akomapalend().contains(StepWork)){
                fillInJobInfoBtn.setText(getString(R.string.vip_info_go));
                fillInJobInfoBtn.setTextColor(Color.parseColor("#FF49280B"));
                fillInJobInfoBtn.setBackgroundResource(R.drawable.back_gradient_yellow_round_c_b);
                fillInJobInfoBtn.setOnClickListener(v -> {

                    HttpHelper.inst().submitEvent("VIP","JOB_INFO_CLICK","");

                    String[] homePermissions = AppAkomapalendConfigCustomize.instance().getHomePermission_akomapalend();

                    if (AkomapaLendUtil.permissionsHasAgree(this, homePermissions)) {
                        //device info upload
                        try {
                            if (AkomapaLendUtil.hasLogin()) {
                                AkomapalendAnalyticsUtil.INSTANCE.saveDeviceS2SInfo();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        //申请流程
                        HttpHelper.inst().process(this,() -> {
                            //无流程:跳转到申请页
                            if (ProcessInAkomapalendfo.instance().getSteps_akomapalend().isEmpty())
                                startActivity(new Intent(this, LoanApplyActivity.class));
                                //有流程:跳转到流程页
                            else startActivity(new Intent(this, MessageActivity.class));
                        });

                    } else
                        EasyPermissions.requestPermissions(this, getString(R.string.request_permission_all), PermissionCHome, homePermissions);

                });
            }

            else {
                fillInJobInfoBtn.setOnClickListener(null);
                fillInJobInfoBtn.setText(getString(R.string.vip_info_received));
                fillInJobInfoBtn.setTextColor(Color.parseColor("#80FFFFFF"));
                fillInJobInfoBtn.setBackgroundResource(R.drawable.back_brown_round_c);
            }
        }

        HttpHelper.inst().fUSerData(this::refreshUserInfo);

    }

    //刷新用户数据
    private void refreshUserInfo(){

        String userAvatarPath = PersAkomapalendonalInfo.instance().getUserAvatar();
        showUserAvatar(userAvatarPath);

        String fullName = PersAkomapalendonalInfo.instance().getFullName();
        if (TextUtils.isEmpty(fullName)) userNameTv.setText(getString(R.string.personal_no_name));
        else userNameTv.setText(fullName);

        String gender = PersAkomapalendonalInfo.instance().getUserGender();
        if (TextUtils.isEmpty(gender)) userGenderTv.setText(getString(R.string.personal_gender_unknown));
        else userGenderTv.setText(gender);

        expValueTv.setText(String.valueOf(PersAkomapalendonalInfo.instance().getExpValue()));
        refreshVipGrade();

    }

    private void refreshVipGrade(){

        int grade = PersAkomapalendonalInfo.instance().getGrade();
        int toNextExp = PersAkomapalendonalInfo.instance().getNextGradeExp();

        switch (grade){
            case 3:
                vipBgView.setBackgroundResource(R.drawable.back_green_round_c);
                vipImgIv.setBackgroundResource(R.drawable.image_diamond_3);
                vipTv.setTextColor(getColor(R.color.color_vip_3));
                vipExpDescTv.setText(getString(R.string.personal_exp_max_desc));
                vipCpb.refresh(1,1,
                        getColor(R.color.color_vip_bg_3),
                        getColor(R.color.color_vip_progress_start_3),
                        getColor(R.color.color_vip_3));
                break;
            case 2:
                vipBgView.setBackgroundResource(R.drawable.back_v2);
                vipImgIv.setBackgroundResource(R.drawable.image_diamond_2);
                vipTv.setTextColor(getColor(R.color.color_vip_2));
                vipExpDescTv.setText(getString(R.string.personal_exp_increase_to_vip3,toNextExp));
                vipCpb.refresh(200, 200-toNextExp,
                        getColor(R.color.color_vip_bg_2),
                        getColor(R.color.color_vip_progress_start_2),
                        getColor(R.color.color_vip_2));
                break;
            default:
                vipBgView.setBackgroundResource(R.drawable.backage_v1);
                vipImgIv.setBackgroundResource(R.drawable.image_diamond);
                vipTv.setTextColor(getColor(R.color.color_vip_1));
                vipExpDescTv.setText(getString(R.string.personal_exp_increase_to_vip2,toNextExp));
                vipCpb.refresh(100,100-toNextExp,
                        getColor(R.color.color_vip_bg_1),
                        getColor(R.color.color_vip_progress_start_1),
                        getColor(R.color.color_vip_1));
        }

        vipTv.setText(getString(R.string.personal_vip,grade));

    }

    private void showUserAvatar(String imgPath){

        Runnable requestAvatarRunnable = () -> {
            if (TextUtils.isEmpty(imgPath) || !imgPath.startsWith("http")) return;
            try {
                URL url = new URL(imgPath);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode()==200){
                    InputStream inputStream = connection.getInputStream();
                    User_Avatar = AkomapaLendUtil.circleBitmap(BitmapFactory.decodeStream(inputStream));;
                    runOnUiThread(() -> userAvatarIv.setImageBitmap(User_Avatar));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        };

        if (User_Avatar!=null){
            userAvatarIv.setImageBitmap(User_Avatar);
            new Thread(requestAvatarRunnable).start();
        }

        else {
            userAvatarIv.setImageResource(R.drawable.image_black_sun);
            new Thread(requestAvatarRunnable).start();
        }

    }

    //获取拍照的照片数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode== OcrVieAkomapalendwManager.Flag_StartCam_akomapalendera){
            onPhotoGet_akomapalend();
        }
    }

    //Permission处理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (requestCode == PermissionCCamera){
            onCameraPermissionAgree_akomapalend();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode == PermissionCCamera) {
            if (EasyPermissions.somePermissionPermanentlyDenied(this, perms))
                new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        if (requestCode == PermissionCCamera)
            EasyPermissions.requestPermissions(this,
                    getString(R.string.request_permission_camera),
                    PermissionCCamera,
                    Manifest.permission.CAMERA);
    }

    @Override
    public void onRationaleDenied(int requestCode) {}

    private void startCamera() {

        HttpHelper.inst().submitEvent("VIP","START_CAMERA_CLICK","");

        cameraRunnable = () -> {
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            String imageFilePath = this.getImageFilePath_akomapalend();
            File imageFile = new File(imageFilePath);
            imagePath = imageFilePath;
            String providerAuthority = BaseContext.instance().getPackageName() + ".file_provider";
            uri = FileProvider.getUriForFile(BaseContext.instance(), providerAuthority, imageFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, OcrVieAkomapalendwManager.Flag_StartCam_akomapalendera);
        };

        if (!AkomapaLendUtil.permissionsHasAgree(this, Manifest.permission.CAMERA)) {
            EasyPermissions.requestPermissions(this,
                    getString(R.string.request_permission_camera),
                    PermissionCCamera, Manifest.permission.CAMERA);
        } else cameraRunnable.run();
    }

    private void openAlbum() {

        HttpHelper.inst().submitEvent("VIP","OPEN_ALBUM_CLICK","");

        if (pickMediaLauncher !=null)
            pickMediaLauncher.launch(
                    new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build()
            );
    }


    public void onCameraPermissionAgree_akomapalend(){
        if (cameraRunnable !=null) cameraRunnable.run();
    }

    private String getImageFilePath_akomapalend() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSandboxFolderPath_akomapalend();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    private String getSandboxFolderPath_akomapalend() {
        String inAppFolder = BaseContext.instance().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += AkomapaLendConfigs.MyProduct;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }


    public void onPhotoGet_akomapalend() {
        if (uri == null) {
            Toast.makeText(this, getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(imagePath)) {
            ImageConvert.startConvertImage(
                    new File(imagePath),
                    (localPath, thumpImg) -> {
                        new Thread(() -> HttpHelper.inst().saveImage(this,localPath,() -> {
                            //上传完成
                            runOnUiThread(() -> {
                                User_Avatar = AkomapaLendUtil.circleBitmap(thumpImg);
                                userAvatarIv.setImageBitmap(User_Avatar);
                            });
                            //保存头像地址
                            PersAkomapalendonalInfo.instance().setUserAvatar(OtheAkomapalendrsInfo.instance().getImgPath_akomapalend());
                            PersAkomapalendonalInfo.instance().uploadUserInfo(null,null);
                        })).start();
                    }
            );
        } else {
            Toast.makeText(this, getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
        }
    }

}